﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WoChu.RfClient.Entity;
using WoChu.RfClient.Common;
using WoChu.CF.BaseFrame.Util;

namespace WoChu.RfClient.Duty
{
    public partial class FrmOnShelves : Form
    {
        public FrmOnShelves()
        {
            InitializeComponent();
        }

        private static Dictionary<string, LocationGoodsInfo> _dictLocationGoods = null;
        public static Dictionary<string, LocationGoodsInfo> dictLocationGoods
        {
            get
            {
                if (_dictLocationGoods == null) _dictLocationGoods = new Dictionary<string, LocationGoodsInfo>();
                return _dictLocationGoods;
            }
        }

        private static Dictionary<string, LocationGoodsInfo> _dictLocation = null;
        public static Dictionary<string, LocationGoodsInfo> dictLocation
        {
            get
            {
                if (_dictLocation == null) _dictLocation = new Dictionary<string, LocationGoodsInfo>();
                return _dictLocation;
            }
        }

        private static List<LocationGoodsInfo> _lstLocationGoods = null;
        public static List<LocationGoodsInfo> lstLocationGoods
        {
            get
            {
                if (_lstLocationGoods == null) _lstLocationGoods = new List<LocationGoodsInfo>();
                return _lstLocationGoods;
            }
        }

        private static int iSort = 0;

        private void FrmOnShelves_Load(object sender, EventArgs e)
        {
            txtBarCode.Focus();
        }
        //显示扫描行
        private void SelectionBright()
        {
            //if (lstLocationGoods == null || lstLocationGoods.Count <= 0) return;
            ////设置已扫描的为加亮
            //List<LocationGoodsInfo> _LocationGoods = lstLocationGoods.FindAll(o => o.Selected);
            //foreach (var _item in _LocationGoods)
            //{
            //    this.dbGridOnShelves.Select(lstLocationGoods.IndexOf(_item));

            //    this.dbGridOnShelves.SelectionBackColor = Color.Green;
            //}
            if (lstLocationGoods == null || lstLocationGoods.Count <= 0) return;
            string barNo = txtBarCode.Text.Trim();
            if (string.IsNullOrEmpty(barNo)) return;
            if (barNo.Length == 18 || barNo.Length == 17 || barNo.Length == 20)
            {
                int curIndex = lstLocationGoods.FindIndex(x => x.GOODSBATCHCODE == barNo);
                dbGridOnShelves.Select(curIndex);
                this.dbGridOnShelves.SelectionBackColor = Color.Green;
            }

        }
        //扫描排序
        private void Sort(LocationGoodsInfo locationGoods)
        {
            locationGoods.Sort = -1;
            lstLocationGoods.Sort((x, y) =>
            {
                return x.Sort.CompareTo(y.Sort);
            });
            this.dbGridOnShelves.Refresh();

            locationGoods.Sort = iSort++;
        }
        //商品批次条码回车操作
        private void txtBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            try
            {
                string _barCode = txtBarCode.Text.Trim();
                if (string.IsNullOrEmpty(_barCode))
                {
                    MessageBox.Show("请扫描商品条码！");
                    return;
                }

                Cursor.Current = Cursors.WaitCursor;

                if (_barCode.Length == 18) //处理商品
                {
                    string strs0 = '0'.ToString();
                    string strs1 = '1'.ToString();
                    if (!_barCode.StartsWith(strs0) && !_barCode.StartsWith(strs1))
                    {
                        MessageBox.Show("请扫描正确的上架条码！");
                        txtBarCode.SelectAll();
                        return;
                    } 
                }
                else if (_barCode.Length == 17 || _barCode.Length == 20)
                {
                    if (!_barCode.StartsWith("WOC"))
                    {
                        MessageBox.Show("请扫描正确的上架条码！");
                        txtBarCode.SelectAll();
                        return;
                    }
                }
                else  //处理货位
                {
                    MessageBox.Show("请扫描正确的上架条码！");
                    txtBarCode.SelectAll();
                    return;

                }
                string cretedtxt = _barCode.Substring(_barCode.Length - 8, 5);
                try
                {
                    DateTime createdate = DateTime.ParseExact("201" + cretedtxt, "yyyyMMdd", null);
                    if (createdate > DateTime.Now)
                    {
                        MessageBoxEx.Show("生产日期" + cretedtxt + "，不能大于当前日期！");
                        txtBarCode.SelectAll();
                        return;
                    }
                }
                catch
                {
                    MessageBoxEx.Show("生产日期" + cretedtxt + "错误，请扫描正确的条码！");
                    txtBarCode.SelectAll();
                    return;
                }
                LocationGoodsInfo lgitem = lstLocationGoods.Find(x => x.GOODSBATCHCODE == _barCode);
                if (lgitem != null)
                {
                    //LocationGoodsInfo _LocationGoods = dictLocationGoods[_barCode];
                    //lgitem.QTY += 1; 
                    txtQty.ReadOnly = lgitem.PURUNITQTY == 1 ? true : false;
                    //排序
                    Sort(lgitem);
                    //设置已扫描的为加亮
                    //SelectionBright();
                }
                else
                {
                    string _Code = _barCode.Substring(0, _barCode.Length - 8);
                    var result = Duty.OnShelvesUIRule.NewInstance.GetLocationGoodsInfo(_Code).DATA;

                    if (result != null)
                    { 
                        //if (!result.QUALITYSTATUS.Equals("0"))
                        //{
                        //    MessageBox.Show("商品:" + result.GOODSNAME +"过保或临保不允许下架！");
                        //    txtBarCode.SelectAll();
                        //    return;
                        //}
                        //验证商品是否有货位关联数据
                        if (result.LOCATIONID == 0)
                        {
                            MessageBox.Show(string.Format("{0} 无货位关联 \n 可能是新品！", _Code));
                            txtBarCode.SelectAll();
                        }
                        else
                        {

                            var _LocationGoods = result;
                            _LocationGoods.QTY = 0;
                            _LocationGoods.GOODSBATCHCODE = _barCode;
                            lstLocationGoods.Add(_LocationGoods);

                            txtQty.ReadOnly = _LocationGoods.PURUNITQTY == 1 ? true : false;
                            //dictLocationGoods.Add(_barCode, _LocationGoods);

                            //if (!dictLocation.Keys.Contains(_LocationGoods.LOCATIONCODE))
                            //{
                            //    dictLocation.Add(_LocationGoods.LOCATIONCODE, _LocationGoods);
                            //}

                            //排序
                            Sort(_LocationGoods);
                            //设置已扫描的为加亮
                            //SelectionBright();
                        }
                    }
                    else
                    {
                        MessageBox.Show("没有找到匹配的数据！");
                        txtBarCode.SelectAll();
                    }
                }

                this.OnShelvesSource.DataSource = null;
                this.OnShelvesSource.DataSource = lstLocationGoods;
                this.dbGridOnShelves.DataSource = this.OnShelvesSource;
                this.dbGridOnShelves.Refresh();
                SelectionBright();

                txtQty.Text = "0";
                txtMinQty.Text = "0";
                if (txtQty.ReadOnly)
                {
                    txtMinQty.Focus();
                    txtMinQty.SelectAll();
                }
                else
                {
                    txtQty.Focus();
                    txtQty.SelectAll();
                }
            }
            catch (Exception ex)
            {
                txtBarCode.Focus();
                txtBarCode.SelectAll();
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        //提交操作
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                string objType = cbObjectType.Text.Trim();
                if (string.IsNullOrEmpty(objType))
                {
                    MessageBoxEx.Show("请选择上架原因！！");
                    return;
                }
                if (lstLocationGoods != null && lstLocationGoods.Count > 0)
                {
                    if (WoChu.CF.BaseFrame.Util.MessageBoxEx.Question("是否提交？") == DialogResult.No) return;

                    List<LocationGoodsInfo> lgItem0 = lstLocationGoods.FindAll(x => x.QTY == 0);
                    if (lgItem0.Count > 0)
                    {
                        MessageBoxEx.Show(string.Format("有{0}条数据的上架数量等于0，请检查再提交？", lgItem0.Count));
                        return;
                    }
                    foreach (var item in lstLocationGoods)
                    {
                        if (item.QTY == 0)
                            lstLocationGoods.Remove(item);
                    }

                    var re = Duty.OnShelvesUIRule.NewInstance.SetOnShelves(LoginBean.Instance.USERCODE, objType, lstLocationGoods);

                    if (re.RESULT.Equals("1"))
                    {
                        lstLocationGoods.Clear();
                        dictLocationGoods.Clear();
                        dictLocation.Clear();
                        this.OnShelvesSource.DataSource = null;
                        this.dbGridOnShelves.DataSource = this.OnShelvesSource;
                        this.dbGridOnShelves.Refresh();

                        txtBarCode.Text = string.Empty;
                        txtQty.Text = string.Empty;
                        txtMinQty.Text = string.Empty;
                        txtBarCode.Focus();
                        MessageBox.Show("提交成功！");
                    }
                    else
                    {
                        MessageBox.Show("提交失败!\n" + re.MESSAGE);
                        return;
                    }
                }
                else
                {
                    MessageBoxEx.Show("请扫描上架数据再提交！");
                    return;
                }
            }
            catch (Exception ex)
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        //回车小数量操作
        private void txtMinQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            string _txtMinQty = this.txtMinQty.Text.Trim();

            if (!string.IsNullOrEmpty(_txtMinQty))
            {
                decimal maxQty = 0;
                decimal minQty = 0;
                try
                {
                    maxQty = Convert.ToDecimal(this.txtQty.Text.Trim());
                    minQty = Convert.ToDecimal(_txtMinQty);
                }
                catch
                {
                    WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不正确!");
                    this.txtMinQty.Text = string.Empty;
                    this.txtMinQty.Focus();
                    return;
                }

                if (maxQty < 0 || minQty < 0)
                {
                    MessageBox.Show("上架数量不能小于0");
                    return;
                }

                //修改实拣量
                if (lstLocationGoods.Count == 0)
                {
                    MessageBox.Show("请选中需改变数量的数据行！");
                    return;
                }
                LocationGoodsInfo _LocationGoods = lstLocationGoods[dbGridOnShelves.CurrentCell.RowNumber];
                decimal odds = _LocationGoods.PURUNITQTY;
                //decimal onQty = _Qty + Math.Round(minQty / odds, 3);
                decimal onQty = maxQty * odds + minQty;
                if (onQty <= 0)
                {
                    MessageBox.Show("上架数量不能小于等于0！");
                    return;
                }

                string _Code = _LocationGoods.GOODSBATCHCODE.Substring(0, _LocationGoods.GOODSBATCHCODE.Length - 8);
                //查询当日该商品是否上架过相同数量，是则提示
                var re = Duty.OnShelvesUIRule.NewInstance.CheckOnShelvesGoodsQTY(_Code, Convert.ToInt16(onQty));
                if (re.RESULT.Equals("0"))
                {

                    if (MessageBoxEx.Question(string.Format("商品:{0}当日已有相同数量上架记录, \n 是否确认要继续上架？", _Code)) == DialogResult.No)
                        return;
                }


                _LocationGoods.QTY = onQty;
                _LocationGoods.MAXQTY = maxQty;        //+ Math.Round(minQty / odds, 3);
                _LocationGoods.MINQTY = minQty;
                this.OnShelvesSource.DataSource = lstLocationGoods;
                this.dbGridOnShelves.DataSource = this.OnShelvesSource;
                this.dbGridOnShelves.Refresh();
                //设置已扫描的为加亮
                SelectionBright();

                this.txtQty.Text = string.Empty;
                this.txtMinQty.Text = string.Empty;
                this.txtBarCode.Text = string.Empty;
                this.txtBarCode.Focus();
            }
            else
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不能为空!");
                return;
            }

            

        }
        //回车大数量操作
        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            if (!string.IsNullOrEmpty(this.txtQty.Text.Trim()))
            {
                decimal maxQty = 0;
                try
                {

                    maxQty = Convert.ToDecimal(this.txtQty.Text.Trim());
                }
                catch
                {
                    WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不正确!");
                    this.txtMinQty.Text = string.Empty;
                    this.txtMinQty.Focus();
                    return;
                }

                if (maxQty < 0)
                {
                    MessageBox.Show("上架数量不能小于0");
                    return;
                }
            }
            else
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不能为空!");
                return;
            }
            this.txtMinQty.Focus();
            this.txtMinQty.SelectAll();
 
            
        }
        //关闭窗体
        private void FrmOnShelves_Closed(object sender, EventArgs e)
        {
            //System.Reflection.Assembly ass = System.Reflection.Assembly.Load("WoChu.RfClient.Login");
            //Type type = ass.GetType("WoChu.RfClient.Login.FrmMain");
            //Object o = Activator.CreateInstance(type);
            //System.Reflection.MethodInfo mi = type.GetMethod("Show"); 
            //mi.Invoke(o, null);
            if (lstLocationGoods != null && lstLocationGoods.Count > 0)
            {
                if (MessageBoxEx.Question("退出是否清空当前数据？") == DialogResult.Yes)
                {
                    lstLocationGoods.Clear();
                    dictLocationGoods.Clear();
                    dictLocation.Clear();
                }
            }
            this.Close();
            this.Dispose();
        }
        //关闭窗体提示
        private void FrmOnShelves_Closing(object sender, CancelEventArgs e)
        {
            if (MessageBoxEx.Question("将退出该窗体，确认是否退出？") == DialogResult.No)
                e.Cancel = true;

        }
        //双击删除操作
        private void dbGridOnShelves_DoubleClick(object sender, EventArgs e)
        {
            int curIndex = dbGridOnShelves.CurrentRowIndex;
            if (curIndex < 0) return;
            try
            {
                string gbCode = dbGridOnShelves[curIndex, 7].ToString();
                LocationGoodsInfo curItem = lstLocationGoods.Find(x => x.GOODSBATCHCODE == gbCode);
                string ltCode = curItem.LOCATIONCODE;
                string gbName = curItem.GOODSNAME;

                string Message = string.Format("货位:{0}, 名称:{1}, 商品批次号:{2}, \n 是否删除该数据？", ltCode, gbName, gbCode);
                if (MessageBoxEx.Question(Message) == DialogResult.Yes)
                {
                    lstLocationGoods.Remove(curItem);
                    dictLocationGoods.Remove(gbCode);
                    this.OnShelvesSource.DataSource = null;
                    this.OnShelvesSource.DataSource = lstLocationGoods;
                    this.dbGridOnShelves.DataSource = this.OnShelvesSource;
                    this.dbGridOnShelves.Refresh();
                    this.txtQty.Text = string.Empty;
                    this.txtMinQty.Text = string.Empty;
                    this.txtBarCode.Text = string.Empty;
                    this.txtBarCode.Focus();
                }
            }
            catch (Exception ex)
            {
                TraceEx.Write(ex.Message);
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("删除数据失败!");
            }
            finally
            {
                txtBarCode.Focus();
                txtBarCode.SelectAll();
            }


        } 
        //单击选择
        private void dbGridOnShelves_Click(object sender, EventArgs e)
        {
            int curIndex = dbGridOnShelves.CurrentRowIndex;
            if (curIndex < 0) return;
            string gbCode = dbGridOnShelves[curIndex, 7].ToString();
            LocationGoodsInfo curItem = lstLocationGoods.Find(x => x.GOODSBATCHCODE == gbCode);
            
            txtBarCode.Text = gbCode; 
            txtQty.ReadOnly = curItem.PURUNITQTY == 1 ? true : false; 
            decimal odds = curItem.PURUNITQTY;
            decimal onQty = curItem.QTY;
            if (txtQty.ReadOnly)
            {
                txtMinQty.Text = onQty.ToString();
                txtQty.Text = "0"; 
                txtMinQty.Focus();
                txtMinQty.SelectAll();
            }
            else
            { 
                //txtQty.Text = Math.Floor((double)onQty).ToString();
                //txtMinQty.Text = Math.Round((onQty % 1) * odds).ToString();
                txtQty.Text = curItem.MAXQTY.ToString();//Math.Round(onQty / odds).ToString();
                txtMinQty.Text = curItem.MINQTY.ToString(); //(onQty % odds).ToString();
                txtQty.Focus();
                txtQty.SelectAll();
            }

            SelectionBright();
        }
 

    }
}